package com.jlnk.androidfmc.model;

import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_CATEGORY_ID;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_DESCRIPTION;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_ID;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_IMAGE_PATH;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_NAME;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_PRICE;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.TABLE_PRODUCTS;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jlnk.androidfmc.database.ProductDatabaseHelper;
import com.jlnk.androidfmc.entity.Product;

import java.util.ArrayList;
import java.util.List;

public class RecommendModel {
    private ProductDatabaseHelper databaseHelper;

    public interface LoadProductsCallback {
        void onProductsLoaded(List<Product> productList);
        void onError();
    }

    public RecommendModel(Context context) {
        this.databaseHelper = new ProductDatabaseHelper(context);
    }

    public void getProducts(final LoadProductsCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = databaseHelper.getReadableDatabase();
                Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PRODUCTS, null);

                List<Product> productList = new ArrayList<>();
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        String id = cursor.getString(cursor.getColumnIndex(COLUMN_PRODUCT_ID));
                        String name = cursor.getString(cursor.getColumnIndex(COLUMN_PRODUCT_NAME));
                        String description = cursor.getString(cursor.getColumnIndex(COLUMN_PRODUCT_DESCRIPTION));
                        String imagePath = cursor.getString(cursor.getColumnIndex(COLUMN_PRODUCT_IMAGE_PATH));
                        int categoryId = cursor.getInt(cursor.getColumnIndex(COLUMN_PRODUCT_CATEGORY_ID));
                        double price = cursor.getDouble(cursor.getColumnIndex(COLUMN_PRODUCT_PRICE));

                        Product product = new Product(id, name, description, imagePath, categoryId, price);
                        productList.add(product);
                    }
                    cursor.close();
                }
                db.close();

                if (productList != null && !productList.isEmpty()) {
                    callback.onProductsLoaded(productList);
                } else {
                    callback.onError();
                }
            }
        }).start();
    }
}